/**
 * $Id$
 *
 * Copyright (c) 2014 ChinaSoft International, Ltd. All rights reserved
 * JointForce Project
 *
 */
package com.csi.jf.crucible.api.crucible;

import java.io.IOException;

import com.chinasofti.ro.bizframework.modules.json.JSONArray;
import com.chinasofti.ro.bizframework.modules.json.JSONObject;
import com.csi.jf.crucible.api.util.ApiUtils;
import com.csi.jf.crucible.ptservice.model.PrjAssociate;
import com.icss.j2ee.util.http.HttpClientException;

/**
 * @Title: ApiTestReviews.java
 * @Description: <br>
 *               <br>
 * @Company: Chinasofti
 * @Created on 2014-7-4 下午3:25:16
 * @author zhangmh
 * @version $Revision: 1.0 $
 * @since 1.0
 */
public class ApiTestReviews {
    
    private RestClient client = new RestClient();
    
    public static void main(String[] args) throws Exception{
        ApiTestReviews test = new ApiTestReviews();
//        test.testReviewCreate();
        test.repositoryBrowse();
//        test.testCreateReviewWithModel();
//        test.transitionReview();
    }
    
    /**
     * Get all reviews as a list of ReviewData structures. Note that this may return a lot of data, so using /reviews-v1/filter/<filter> is usually better.
     * The state parameter is a comma separated list of state names from the set Draft, Approval, Review, Summarize, Closed, Dead, Rejected, Unknown.
     * @param state string only return reviews that are in these states.
     * @throws HttpClientException
     * @throws IOException
     * @return
     * {
        "reviewData": [
            {
                "projectKey": "PTS-TEST", 
                "name": "add:new project", 
                "description": "", 
                "author": {
                    "userName": "zhaochen", 
                    "displayName": "zhao chen", 
                    "avatarUrl": "http://ay140618171910689741z:8060/avatar/zhaochen?s=48", 
                    "SONAR_URL": "/user/zhaochen"
                }, 
                "creator": {
                    "userName": "zhaochen", 
                    "displayName": "zhao chen", 
                    "avatarUrl": "http://ay140618171910689741z:8060/avatar/zhaochen?s=48", 
                    "SONAR_URL": "/user/zhaochen"
                }, 
                "permaId": {
                    "id": "PTS-TEST-1"
                }, 
                "permaIdHistory": [
                    "PTS-TEST-1"
                ], 
                "state": "Review", 
                "type": "REVIEW", 
                "allowReviewersToJoin": false, 
                "metricsVersion": 1, 
                "createDate": "2014-07-01T17:46:26.823+0800", 
                "dueDate": "2014-07-10T18:00:00.000+0800"
            }
        ]
    }
     */
    public void testRevivewAllList() throws HttpClientException, IOException{
        String url = "/rest-service/reviews-v1";
        client.doGet(url);
    }
    
    /**
     *  Create a review from the given createReview element.
        The sub-elements of the createReview element determine what type of review is created and how it is populated. The following rules govern which sub-elemnts can be present and how they are used in the review creation process
        
        If the snippet element is specified a reviewData element must be supplied and no other elements may be supplied.
        At least one of reviewData and detailedReviewData must be supplied. If both are supplied, the reviewers element of the detailedReviewData element is used. All other elements of detailedReviewData are ignored.
        If the state element is present and has the value of "Review" in the reviewData (or detailedReviewData if used), then the review will be approved at creation, where allowed
        The changesets and path elements can be supplied with either the reviewData or detailedReviewData elements.
     * @throws HttpClientException
     * @throws IOException
     */
    public void testReviewCreate() throws HttpClientException,IOException{
        String url = "/rest-service/reviews-v1";
        String json = "{"+
          "\"reviewData\" : {"+
            "\"projectKey\" : \"testkey\","+
            "\"name\" : \"Review测试\","+
            "\"description\" : \"Description or statement of objectives for this example review.\","+
            "\"author\" : {"+
              "\"userName\" : \"zhangmh\","+
              "\"displayName\" : \"zhang.m.h\","+
              "\"avatarUrl\" : \"http://foo.com/avatar\""+
            "},"+
            "\"moderator\" : {"+
              "\"userName\" : \"zhaochen\","+
              "\"displayName\" : \"zhaochen the Moderator\","+
              "\"avatarUrl\" : \"http://foo.com/avatar\""+
            "},"+
            "\"creator\" : {"+
              "\"userName\" : \"fenghaibing\","+
              "\"displayName\" : \"fenghaibing Krustofski\","+
              "\"avatarUrl\" : \"http://foo.com/avatar\""+
            "},"+
            "\"permaId\" : {"+
              "\"id\" : \"PTS-TEST-21\""+
            "},"+
            "\"permaIdHistory\" : [ \"PTS-TEST-21\" ],"+
            "\"type\" : \"REVIEW\","+
            "\"allowReviewersToJoin\" : false,"+
            "\"metricsVersion\" : 4,"+
            "\"createDate\" : \"2014-07-06T15:15:23.922+0200\","+
            "\"dueDate\" : \"2014-07-07T15:15:23.922+0200\""+
            //"\"jiraIssueKey\" : \"\""+//\"FOO-6754\""+
          "}"+
          //"\"patch\" : \"Index: emptytests/notempty/a.txt\ndiff -u -N -r1.31 -r1.32\n--- emptytests/notempty/a.txt\t22 Sep 2004 00:38:15 -0000\t1.31\n+++ emptytests/notempty/a.txt\t5 Dec 2004 01:04:25 -0000\t1.32\n@@ -4,4 +4,5 @@\n hello there :D\n CRU-123\n http://madbean.com/blog/\n-!\n\\ No newline at end of file\n+!\n+foobie\n\\ No newline at end of file\nIndex: test/a.txt\n===================================================================\ndiff -u -N -r1.31 -r1.32\n--- test/a.txt\t22 Sep 2004 00:38:15 -0000\t1.31\n+++ test/a.txt\t5 Dec 2004 01:04:25 -0000\t1.32\n@@ -4,4 +4,5 @@\n hello there :D\n CRU-123\n http://madbean.com/blog/\n-!\n\\ No newline at end of file\n+!\n+foobie\n\\ No newline at end of file\","+
          //"\"anchor\" : {"+
          //  "\"anchorPath\" : \"/\","+
          //  "\"anchorRepository\" : \"REPO\","+
          //  "\"stripCount\" : 2"+
          //"},"+
          //"\"changesets\" : {"+
          //  "\"changesetData\" : [ ],"+//{\"id\" : \"63452\"}
          //  "\"repository\" : \"CrucibleTest\""+
          //"}"+
        "}";
        client.doPost(url, json);
        /*
         * {
            "reviewData": [
                {
                    "projectKey": "PTS-TEST", 
                    "name": "add:new project", 
                    "description": "", 
                    "author": {
                        "userName": "zhaochen", 
                        "displayName": "zhao chen", 
                        "avatarUrl": "http://ay140618171910689741z:8060/avatar/zhaochen?s=48", 
                        "SONAR_URL": "/user/zhaochen"
                    }, 
                    "creator": {
                        "userName": "zhaochen", 
                        "displayName": "zhao chen", 
                        "avatarUrl": "http://ay140618171910689741z:8060/avatar/zhaochen?s=48", 
                        "SONAR_URL": "/user/zhaochen"
                    }, 
                    "permaId": {
                        "id": "PTS-TEST-1"
                    }, 
                    "permaIdHistory": [
                        "PTS-TEST-1"
                    ], 
                    "state": "Review", 
                    "type": "REVIEW", 
                    "allowReviewersToJoin": false, 
                    "metricsVersion": 1, 
                    "createDate": "2014-07-01T17:46:26.823+0800", 
                    "dueDate": "2014-07-10T18:00:00.000+0800"
                }
            ]
        }
         */
    }

    /**
     * 
     * @param reviewJson
     * @throws HttpClientException
     * @throws IOException
     * @Created on 2014-7-7 下午5:21:25
     * @author FengHaiBing
     */
    public String createReview(String reviewJson,PrjAssociate pa) throws HttpClientException,IOException{
    	String reviewId=null;
        String url = "/rest-service/reviews-v1";
        String responseJson=client.doPost(url, reviewJson);
        
        if(null==responseJson) return null;
        JSONObject jObject = JSONObject.fromObject(responseJson);
        
        if(jObject == null || jObject.get("permaId") == null) return null;
        JSONObject jb=(JSONObject)jObject.get("permaId");
        reviewId=(String) jb.get("id");
        
        return reviewId;
    }
    
    /**
     * add reviewers for the review whose id is reviewId
     * 
     * @param reviewId
     * @param reviewersNameList  the reviewers' name's list, e.g. "maogx,zhangmh", note this is not a json string here 
     * @throws HttpClientException
     * @throws IOException
     * @Created on 2014-7-11 下午5:52:39
     * @author FengHaiBing
     */
    public void addReviewers(String reviewId, String reviewersNameList) throws HttpClientException, IOException {
//    	String reviewId=null;
        String url = "/rest-service/reviews-v1/" + reviewId + "/reviewers";
        client.doPost(url, reviewersNameList);
    	
    }
    
    public void testAddReviewers() throws HttpClientException, IOException {
		JSONObject reviewer = new JSONObject();
		reviewer.put("userName", "maogx");
		reviewer.put("displayName", "mao guo xin");
		reviewer.put("avatarUrl", "http://foo.com/avatar");

		JSONObject reviewer2 = new JSONObject();
		reviewer2.put("userName", "zhangmh");
		reviewer2.put("displayName", "zhang.m.h");
		reviewer2.put("avatarUrl", "http://foo.com/avatar");
		
		JSONArray ja = new JSONArray();
		ja.add(reviewer);
		ja.add(reviewer2);
 
		JSONObject reviewers = new JSONObject();
		reviewers.put("reviewers", ja);
		String json = reviewers.toString();
		json = ja.toString();
		json = reviewer.toString();
//		json = "maogx,zhangmh";
		json = "maogx";
//		json = "{\"maogx\"}";
		String reviewId = "cru267-10";
		addReviewers(reviewId, json);
    }
    
    
    public void testCreateReviewWithModel() throws HttpClientException, IOException {
    	
		String projectKey = "cru267";
		String name = "PortalJava代码检查专家服务";
		String description = "";
		JSONObject author = new JSONObject();
		author.put("userName", "zhangmh");
		author.put("displayName", "zhang.m.h");
		author.put("avatarUrl", "http://foo.com/avatar");
		
		JSONObject moderator = new JSONObject();
		moderator.put("userName", "jfpts");
		moderator.put("displayName", "jf pts");
		moderator.put("avatarUrl", "http://foo.com/avatar");
		
		JSONObject creator = new JSONObject();
		creator.put("userName", "jfpts");
		creator.put("displayName", "jf pts");
		creator.put("avatarUrl", "http://foo.com/avatar");
		
		JSONObject permaId = new JSONObject();
		permaId.put("id", "PTS-TEST-21");
		
		JSONObject changesets = new JSONObject();
		changesets.put("changesetData", "[]");
		changesets.put("repository", "CrucibleTest");
//		creator.put("repository", "CrucibleTest");
//		name = new String(name.getBytes("UTF-8"), "UTF-8");//java.net.URLEncoder.encode(name,"UTF-8");
		ReviewModel rm = new ReviewModel(projectKey, name, description, author, moderator, creator, permaId, changesets);
		String reviewJson = rm.createReviewModel();
		createReview(reviewJson,null);
    }
    
    /**
     * @param action string the string representation of the action to perform. Valid actions are:
        action:abandonReview -- abandon (i.e. cancel) a review
        action:deleteReview -- permanently delete a review
        action:submitReview -- submit a review to the moderator for approval
        action:approveReview -- approve a review (i.e. issue it to the reviewers)
        action:rejectReview -- reject a review submitted for approval
        action:summarizeReview -- summarize a review
        action:closeReview -- close a review once it has been summarized
        action:reopenReview -- re-open a closed review
        action:recoverReview -- recover an abandoned review
        action:completeReview -- indicate you have completed a review
        action:uncompleteReview -- indicate you have not completed a review, after indicating you have completed a review
     * @throws IOException 
     * @throws HttpClientException 
     */
    public void transitionReview() throws HttpClientException, IOException{
        String url = "/rest-service/reviews-v1/{id}/transition?action={action}";
        url = ApiUtils.formatUrl(url,new String[]{"id","action"},new String[]{"testkey-6","action:closeReview"});
        client.doGet(url);
    }
    
    public void closeReview() throws HttpClientException, IOException{
        String url = "/rest-service/reviews-v1/{id}/close";
        url = ApiUtils.formatUrl(url,new String[]{"id"},new String[]{"testkey-6"});
        client.doGet(url);
    }
    
    public void repositoryBrowse() throws HttpClientException, IOException{
        String url = "/rest-service/repositories-v1/browse/{repo}/{path:.*$}";
        url = ApiUtils.formatUrl(url,new String[]{"repo","path:.*$"},new String[]{"CrucibleTest","/modules/api:.*$"});
        client.doGet(url);
    }
    

}
